<template>
	<view class="work-container">
		<uni-card :is-shadow="false" style="margin-bottom: 20px;">
			<!-- 工单类型选择 -->
			<uni-forms ref="baseForm" label-position="top">
				<uni-title type="h2" title="选择工单类型" align="center"></uni-title>
				<uni-forms-item label="工单分类" required>
					<uni-data-select v-model="orderData.orderType" :localdata="range"
						@change="typechange"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="申请类型" required>
					<uni-data-select v-model="orderData.bidType" :localdata="rangetype"
						@change="bindType"></uni-data-select>
				</uni-forms-item>
			</uni-forms>
			<!-- 动态渲染组件" /> -->
			<component :is="currentFormComponent" :formData="currentFormData" :options2022="Item2022List"
				:options2017="Item2017List" :operation-options="operationList" @update="handleFormUpdate" />
			<button type="primary" @click="handleSave">保存企业信息</button>
		</uni-card>

		<report-selection :items="items" :current="current" @change="handleReportChange" />



<view class="button-container">
			<view class="button-save">
				<button style="flex: 1; margin-bottom: 10px;" type="primary" @click="handleToReprot">下一步</button>
			</view>
			<view class="button-save">
				<button style="flex: 1;" type="warn" @click="goHome">返回首页</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getFoodType,
		getOrderType,
		getBidType,
		addWorkOrder,
		getformat,
		getProject,
		getMedicalType,
		getMedicalDict
	} from '@/api/order'
	import FoodBusinessForm from '@/components/order/FoodBusinessForm.vue'
	import MedicalEquipmentForm from '@/components/order/MedicalEquipmentForm.vue'
	import MultiSelectPopup from '@/components/multi-select-popup/multi-select-popup.vue'
	import ReportSelection from '@/components/order/ReportSelection'
	import FoodProductionForm from '@/components/order/FoodProductionForm.vue'
	export default {
		components: {
			FoodBusinessForm,
			MedicalEquipmentForm,
			ReportSelection,
			FoodProductionForm
		},
		computed: {
			currentFormComponent() {
				return {
					'1': 'FoodBusinessForm',
					'2': 'FoodProductionForm',
					'3': 'MedicalEquipmentForm'
				} [this.orderData.orderType]
			},
			currentFormData() {
				return this.orderData;
			}
		},
		data() {
			return {
				current: 0,
				selectValue: '1',
				orderId: '',
				range: [],
				items: [],
				rangetype: [],
				bidTypeItem: '',
				orderData: {
					orderType: '1',
					bidType: '1',
					acceptNumber: '',
					orderCategory: '',
					operatorName: '',
					operatorPlace: '',
					address: '',
					modeOfOperation: '',
					workLayout2002List: [],
					workLayout2002Item:'',
					workLayout2017List: [],
					workLayout2017Item:'',
					legalPersonName: '',
					leaglCertNo: '',
					enterpriseManagerName: '',
					enterpriseManagerCertNo: '',
					qualityManagerName: '',
					qualityManagerCertNo: '',
					createBy: "",
					workOrderId:""
				},

				Item2022List: {},
				Item2017List: {},
				operationList: {},
				checkText: '' //选中的文本
			}
		},
		onLoad() {
			this.loadFormItems() // 初始化加载默认数据
			this.getMedicalDict('order_type')
			this.getMedicalDict('2022');
			this.getMedicalDict('2017');
			this.getMedicalDict('mode_of_operation')
			this.getMedicalDict('bid_type')
			
		},
		onShow() {
				this.initFormData() // 初始化加载默认数据
			//this.initFormData() ;
		},


		methods: {
			// 统一保存方法
			async handleSave() {
				
				console.log(this.orderData)
				try {
					const postData = {
						...this.orderData
					}; // 明确使用副本
					if (this.orderData.orderType === '3') {
						if (!Array.isArray(postData.workLayout2002List) || postData.workLayout2002List.length === 0) {
							return uni.showToast({
								title: '请选择2002版经营范围',
								icon: 'none'
							})
						}
						if (!Array.isArray(postData.workLayout2017List) || postData.workLayout2017List.length === 0) {
							return uni.showToast({
								title: '请选择2017版经营范围',
								icon: 'none'
							})
						}
					}
					const isMedical = postData.orderType === '3';
					// 通用必填字段验证
					const requiredFields = [
						'orderType', 'bidType', 'operatorName', 'address',
						...(isMedical ? [
							'operatorPlace', 'modeOfOperation',
							'legalPersonName', 'leaglCertNo',
							'enterpriseManagerName', 'enterpriseManagerCertNo',
							'qualityManagerName', 'qualityManagerCertNo'
						] : ['acceptNumber'])
					]

					// 验证字段
					const missingField = requiredFields.find(field => {
						const value = postData[field]
						return !value || (typeof value === 'string' && !value.trim())
					})

					if (missingField) {
						return uni.showToast({
							title: `${this.getFieldName(missingField)}不能为空`,
							icon: 'none'
						})
					}

					// 处理医疗器械特殊字段
					if (this.orderData.orderType === '3') {
						postData.workLayout2002List = this.orderData.workLayout2002List.map(v => ({
							layouTtwo: v
						}))
						postData.workLayout2017List = this.orderData.workLayout2017List.map(v => ({
							layoutSeven: v
						}))
						
						this.orderData.workLayout2002List = this.orderData.workLayout2002List.map(v => ({
							layouTtwo: v
						}))
						this.orderData.workLayout2017List = this.orderData.workLayout2017List.map(v => ({
							layoutSeven: v
						}))
					}

					// 提交数据
					const res = await addWorkOrder(postData)
					if (res.code === 0) {
						uni.showToast({
							title: '保存成功'
						})
						this.orderData.workOrderId=res.data;
						this.orderId = res.data
						uni.setStorageSync('savedEnterprise', this.orderId)
					} else {
						throw new Error(res.msg || '保存失败')
					}
				} catch (error) {
					uni.showToast({
						title: `保存失败: ${error.message}`,
						icon: 'none',
						duration: 3000
					})
					console.error('保存异常:', error)
				}
			},

			// 字段名称映射
			getFieldName(field) {
				const fieldMap = {
					orderType: '工单类型',
					bidType: '申请类型',
					operatorName: '经营者名称',
					address: '地址',
					operatorPlace: '经营场所',
					modeOfOperation: '经营方式',
					legalPersonName: '法人姓名',
					leaglCertNo: '法人证件',
					enterpriseManagerName: '企业负责人姓名',
					enterpriseManagerCertNo: '企业负责人证件',
					qualityManagerName: '质量负责人姓名',
					qualityManagerCertNo: '质量负责人证件',
					acceptNumber: '受理号'
				}
				return fieldMap[field] || '必填字段'
			},
			handleReportChange(value) {
				console.log('value' + value)
				const index = this.items.findIndex(item => item.value === value)
				if (index > -1) {
					this.current = index
					this.selectValue = value
					this.orderData.orderCategory = value
				}
			},
			 handleFormUpdate(partialData) {
			    // 合并子组件传递的更新到 orderData
			    this.orderData = { 
			      ...this.orderData, 
			      ...partialData 
			    }
			    console.log('当前数据:', this.orderData) // 调试用
			  },
			// 新增初始化方法
			initFormData() {

				// 重置设备数据
				this.orderData = {
					orderType: '1',
					bidType: '1',
					acceptNumber: '',
					orderCategory: '',
					operatorName: '',
					operatorPlace: '',
					address: '',
					modeOfOperation: '',
					workLayout2002List: [],
					workLayout2017List: [],
					legalPersonName: '',
					leaglCertNo: '',
					enterpriseManagerName: '',
					enterpriseManagerCertNo: '',
					qualityManagerName: '',
					qualityManagerCertNo: '',
					createBy: "",
					workOrderId:""
				}

				// 重置其他状态
				this.current = 0
				this.selectValue = '0'
				this.orderId = ''

				// 重置多选组件（需要给组件添加ref）
				if (this.$refs.multiSelect2022) this.$refs.multiSelect2022.clear()
				if (this.$refs.multiSelect2017) this.$refs.multiSelect2017.clear()
			},

			typechange(e) {
				console.log("e:" + e);

				this.loadFormItems() // 类型变化时触发数据加载
			},
			bindType(e) {
				//获取当前选取申办类型
				this.bidTypeItem = this.rangetype[e - 1].text;
			},

			radioChange(evt) {
				console.log("evt" + JSON.stringify(evt))
				for (let i = 0; i < this.items.length; i++) {
					if (this.items[i].value === evt.detail.value) {
						this.current = i;
						this.selectValue = this.items[i].value;
						this.orderData.orderCategory = this.selectValue;
						break;
					}
				}

			},
			handleToReprot() {
			/*
				
				if (!this.orderData.workOrderId) {
					return uni.showToast({
						title: '请先填写并保存企业信息',
						icon: 'none'
					});
				}*/

				let targetUrl = '';
				console.log(this.orderData)
				switch (this.selectValue) {
					case '0':
						uni.navigateTo({
							url: `/pages/work/create/food-business/business-work-rule?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}`
						});
						break;
					case '1':
						uni.navigateTo({
							url: `/pages/work/create/food-business/checklist-fifth?operatorName=${encodeURIComponent(this.orderData.operatorName)}&orderCategory=${encodeURIComponent('1')}&address=${encodeURIComponent(this.orderData.address)}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '2':
						uni.navigateTo({
							url: `/pages/work/create/food-business/checklist-fifth?operatorName=${encodeURIComponent(this.orderData.operatorName)}&orderCategory=${encodeURIComponent('2')}&address=${encodeURIComponent(this.orderData.address)}&workOrderId=${encodeURIComponent(this.orderId)}`
						}); // 提交成功后重置表单
						break;
					case '3':
						uni.navigateTo({
							url: `/pages/work/create/food-business/report-technical?workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '4': //跳转到企业主动撤回报表
						uni.navigateTo({
							url: `/pages/work/create/food-business/enterprise-withdraw?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&bindType=${this.bidTypeItem}`
						});
						break;
					case '5': //医疗器械现场检查表
						// 将对象转为 JSON 字符串
						uni.navigateTo({
							url: `/pages/work/create/medical/medical-checklist?equipment=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '6':
						uni.navigateTo({
							url: `/pages/work/create/medical/medical-review?workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '7'://医疗器械-审查
						uni.navigateTo({
							url: `/pages/work/create/medical/medical-checkReport?workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '8':
						uni.navigateTo({
							url: `/pages/work/create/medical/medical-assessor?workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '9': //跳转到医疗器械-企业主动撤回
						uni.navigateTo({
							url: `/pages/work/create/medical/medical-reviewCheck?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&checkText=${this.checkText}&bidTypeItem=${this.bidTypeItem}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;

					case '11': //食品生产选派单

						uni.navigateTo({
							url: `/pages/work/create/food-production/check-assign?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
						case '12': //珠海市食品药品(医疗器械)审评认证中心 食品生产许可现场核查通知书
						
							uni.navigateTo({
								url: `/pages/work/create/food-production/check-notice?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
							});
							break;
							
						
					case '13': //食品、食品添加剂生产许可现场核查首次会议签到表

						uni.navigateTo({
							url: `/pages/work/create/food-production/first-meeting?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '15': //食品、食品添加剂生产许可现场核查报告
						uni.navigateTo({
							url: `/pages/work/create/food-produce/index?workOrderId=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}&orderCategory=15`
						});
						break;

					case '16': //食品、食品添加剂生产许可现场核查末次会议签到表

						uni.navigateTo({
							url: `/pages/work/create/food-production/last-meeting?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '17': //食品技术审评报告
						uni.navigateTo({
							url: `/pages/work/create/food-production/checkReport?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '18': //广东省食品生产许可核查人员廉洁自律承诺书
						uni.navigateTo({
							url: `/pages/work/create/food-production/commit-letter?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					case '19': //食品生产许可现场核查人员工作纪律反馈单
						uni.navigateTo({
							url: `/pages/work/create/food-production/feedback?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
				
					case '20': //食品生产 撤销审查
						uni.navigateTo({
							url: `/pages/work/create/food-production/enterprise-withdraw?orderData=${encodeURIComponent(JSON.stringify(this.orderData))}&workOrderId=${encodeURIComponent(this.orderId)}`
						});
						break;
					default:
						uni.showToast({
							title: '请选择一个选项',
							icon: 'none'
						});
						return;
				}



			},


			async loadFormItems() {
				try {
					const typeMap = new Map([
						[1, 'food_operate_type'],
						[2, 'food_production_type'],
						[3, 'medical_operate_type']
					]);
					
					const orderType = Number(this.orderData.orderType) || 1;
					const type = typeMap.get(orderType) ?? '';

					const res = await getMedicalDict(type)
					if (res.code === 0) {
						this.items = res.data.map(item => ({
							name: item.label,
							value: item.value,

						}))

						this.selectValue = this.items[0].value;
						this.orderData.orderCategory=this.items[0].value;
						this.current = 0;
					}

				} catch (error) {
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					})
				}
			}, //获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {

						switch (type) {
							case '2022':
								this.Item2022List = res.data.map(item => ({
									label: item.label, // 注意字段名需与uni-data-select要求一致
									value: item.value
								}))
								break;
							case '2017':
								this.Item2017List = res.data.map(item => ({
									label: item.label, // 注意字段名需与uni-data-select要求一致
									value: item.value
								}))
								break;
							case 'mode_of_operation': //获取经营方式

								this.operationList = res.data.map(item => ({
									text: item.label, // 注意字段名需与uni-data-select要求一致
									value: item.value
								}))

								break;
							case 'order_type': //获取工单分类
								this.range = res.data.map(item => ({
									text: item.label, // 注意字段名需与uni-data-select要求一致
									value: item.value
								}))

								break;

							case 'bid_type': //获取申办类型

								this.rangetype = res.data.map(item => ({
									text: item.label, // 注意字段名需与uni-data-select要求一致
									value: item.value
								}))
								break;
							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			},
			goHome() {
				this.$tab.navigateBack();
			},
		}
	}
</script>

<style scoped>
	.work-container {
		padding: 10px;
	}

	.form-section {
		margin-bottom: 20px;
	}

	.action-buttons button {
		margin: 15px 20px 0;
	}
	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */
	
		.button-save {
			margin-bottom: 10px;
		}
	
		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */
	
		}
	}
</style>